package com.simple.weibo.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.simple.weibo.bean.User;
import com.simple.weibo.bean.Weibo;
import com.simple.weibo.oauth.OAuth;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author mxf <a href="mailto:maxuefengs@gmail.com">mxf</a>
 *         11-8-15 上午10:53
 * @since version 1.0
 */
public class MainPageUtils {

    public static void setMessagePage(final AlertDialog dialog, final WeiboMainActivity ay, final User user, final ImageButton refreshButton) {

        dialog.show();
        final ListView msgList = (ListView) ay.findViewById(R.id.msgList);
        ImageButton myWeibo = (ImageButton) ay.findViewById(R.id.myWeibo);
        ImageButton commnetWeibo = (ImageButton) ay.findViewById(R.id.commentMe);

        final List<Weibo> list = new ArrayList<Weibo>();
        final MyAdapater ad = new MyAdapater(list, ay, user);

        final List<Weibo> commentList = new ArrayList<Weibo>();
        final WeiboMainActivity.WeiboAdapater commentAd = ay.new WeiboAdapater(commentList);

        msgList.setAdapter(ad);
        msgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
                Object obj = view.getTag();
                if (obj != null) {
                    String id = obj.toString();
                    Intent intent = new Intent(ay, WeiboContextActivity.class);
                    Bundle b = new Bundle();
                    b.putString("id", id);
                    b.putString("userId", user.getUserId());

                    intent.putExtras(b);
                    ay.startActivity(intent);
                }
            }
        });
        final Handler msgHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    ad.notifyDataSetChanged();
                } else {
                    commentAd.notifyDataSetChanged();
                }
                dialog.dismiss();
            }
        };
        new Thread(new Runnable() {
            public void run() {
                getMyWeibo(msgHandler, list, user);
            }
        }).start();
        myWeibo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                msgList.setAdapter(ad);
                refreshButton.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        dialog.show();
                        getCommentWeibo(msgHandler, commentList, user);
                    }
                });
            }
        });
        commnetWeibo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (commentList.size() == 0) {
                    dialog.show();
                    getCommentWeibo(msgHandler, commentList, user);
                }
                msgList.setAdapter(commentAd);
                refreshButton.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        dialog.show();
                        getCommentWeibo(msgHandler, commentList, user);
                    }
                });
            }
        });
    }

    public static void getCommentWeibo(Handler hd, List<Weibo> list, User user) {
        OAuth oauth = new OAuth();
        String url = "http://api.t.sina.com.cn/statuses/mentions.json";
        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(new BasicNameValuePair("source", OAuth.appKey));
        HttpResponse response = oauth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, pairList);
        if (response.getStatusLine().getStatusCode() == 200) {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder sb = new StringBuilder();
                String str = "";
                while ((str = br.readLine()) != null) {
                    System.out.println(str);
                    sb.append(str).append("\r\n");
                }
                String sg = sb.toString();
                JSONArray data = new JSONArray(sg);
                for (int i = 0; i < data.length(); i++) {
                    JSONObject d = data.getJSONObject(i);
                    if (d != null) {
                        JSONObject u = d.getJSONObject("user");

                        //微博id
                        String id = d.getString("id");
                        String userId = u.getString("id");
                        String userName = u.getString("screen_name");
                        String userIcon = u.getString("profile_image_url");

                        String time = d.getString("created_at");
                        Date date = new Date(time);
                        time = new SimpleDateFormat("MM-dd HH:mm:ss").format(date);
                        String text = d.getString("text");
                        Boolean haveImg = false;
                        if (d.has("thumbnail_pic")) {
                            haveImg = true;
                        }
                        if (d.has("retweeted_status")) {
                            JSONObject r = d.getJSONObject("retweeted_status");
                            text += "\r\n$";
                            JSONObject uu = r.getJSONObject("user");
                            text += uu.getString("screen_name") + ":" + r.getString("text")+"$";
                        }
                        Weibo w = new Weibo();
                        w.setId(id);
                        w.setUserId(userId);
                        w.setUserName(userName);
                        w.setUserIcon(userIcon);

                        w.setTime(time);
                        w.setText(text);

                        w.setHaveImage(haveImg);
                        list.add(w);
                    }
                }

                System.out.println(sg);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            hd.sendEmptyMessage(2);
        }
    }

    public static void getMyWeibo(Handler hd, List<Weibo> list, User user) {
        OAuth oauth = new OAuth();
        String url = "http://api.t.sina.com.cn/statuses/user_timeline.json";
        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(new BasicNameValuePair("source", OAuth.appKey));
        HttpResponse response = oauth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, pairList);
        if (response.getStatusLine().getStatusCode() == 200) {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder sb = new StringBuilder();
                String str = "";
                while ((str = br.readLine()) != null) {
                    System.out.println(str);
                    sb.append(str).append("\r\n");
                }
                String sg = sb.toString();
                JSONArray data = new JSONArray(sg);
                for (int i = 0; i < data.length(); i++) {
                    JSONObject d = data.getJSONObject(i);
                    if (d != null) {
                        JSONObject u = d.getJSONObject("user");

                        //微博id
                        String id = d.getString("id");
                        String userId = u.getString("id");
                        String userName = u.getString("screen_name");

                        String time = d.getString("created_at");
                        Date date = new Date(time);
                        time = new SimpleDateFormat("MM-dd HH:mm:ss").format(date);
                        String text = d.getString("text");
                        Boolean haveImg = false;
                        if (d.has("thumbnail_pic")) {
                            haveImg = true;
                        }
                        if (d.has("retweeted_status")) {
                            JSONObject r = d.getJSONObject("retweeted_status");
                            text += "\r\n$";
                            JSONObject uu = r.getJSONObject("user");
                            text += uu.getString("screen_name") + ":" + r.getString("text")+"$";
                        }
                        Weibo w = new Weibo();
                        w.setId(id);
                        w.setUserId(userId);
                        w.setUserName(userName);

                        w.setTime(time);
                        w.setText(text);

                        w.setHaveImage(haveImg);
                        list.add(w);
                    }


                }

                System.out.println(sg);
            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            hd.sendEmptyMessage(1);
        }
    }

    public static class MyAdapater extends BaseAdapter {

        List<Weibo> list = new ArrayList<Weibo>();
        Context context;
        User user;

        public MyAdapater(List<Weibo> list, Context ct, User user) {
            this.list = list;
            context = ct;
            this.user = user;
        }

        public int getCount() {
            return list.size();
        }

        public Object getItem(int position) {
            return list.get(position);
        }

        public long getItemId(int position) {
            return position;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.weibo_content, null);
            }
            ImageView wbicon = (ImageView) convertView.findViewById(R.id.wbicon);
            TextView wbtext = (TextView) convertView.findViewById(R.id.wbtext);
            TextView wbtime = (TextView) convertView.findViewById(R.id.wbtime);
            TextView wbuser = (TextView) convertView.findViewById(R.id.wbuser);
            ImageView wbimage = (ImageView) convertView.findViewById(R.id.wbimage);

            final Weibo wb = list.get(position);

            convertView.setTag(wb.getId());
            wbuser.setText(wb.getUserName());
            wbtime.setText(wb.getTime());
            wbtext.setText(wb.getText(), TextView.BufferType.SPANNABLE);
            MainPageUtils.highLightTex(wbtext,"#","#");
            MainPageUtils.highLightTex(wbtext,"@",":");
            MainPageUtils.highLightTex(wbtext,"@"," ");
            MainPageUtils.highLightTex(wbtext,"http://"," ");
            MainPageUtils.highLightTex2(wbtext,"$","$");

            if (wb.getHaveImage()) {
                wbimage.setImageResource(R.drawable.t_sina);
            }
            wbicon.setImageDrawable(user.getIcon());

            return convertView;
        }

    }

    public static void highLightTex(TextView textView, String start, String end) {
        Spannable sp = (Spannable) textView.getText();
        String text = textView.getText().toString();
        int n = 0;
        int s = -1;
        int e = -1;
        while (n < text.length()) {
            s = text.indexOf(start, n);
            if (s != -1) {
                e = text.indexOf(end, s + start.length());
                if (e != -1) {
                    e = e + end.length();
                } else {
                    e = text.length();
                }
                n = e;
                sp.setSpan(new ForegroundColorSpan(Color.BLUE), s, e, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                s = e = -1;
            } else {
                n = text.length();
            }
        }
    }
     public static void highLightTex2(TextView textView, String start, String end) {
        Spannable sp = (Spannable) textView.getText();
        String text = textView.getText().toString();
        int n = 0;
        int s = -1;
        int e = -1;
        while (n < text.length()) {
            s = text.indexOf(start, n);
            if (s != -1) {
                e = text.indexOf(end, s + start.length());
                if (e != -1) {
                    e = e + end.length();
                } else {
                    e = text.length();
                }
                n = e;
                sp.setSpan(new ForegroundColorSpan(Color.GREEN), s, e, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                s = e = -1;
            } else {
                n = text.length();
            }
        }
    }
}
